import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { showToast } from 'vant'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      isLogin: false,
      title: '首页'
    }
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
    meta: {
      isLogin: false,
      title: '关于'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: {
      isLogin: false,
      title: '登录'
    }
  },
  {
    path: '/my',
    name: 'my',
    component: () => import('../views/MyView.vue'),
    meta: {
      isLogin: true,
      title: '我的'
    }
  },
  {
    path: '/personHome',
    name: 'personHome',
    component: () => import('../views/PersonHome.vue'),
    meta: {
      isLogin: false,
      title: '个人主页'
    }
  },
  {
    path: '/personInfo',
    name: 'personInfo',
    component: () => import('../views/PersonInfo.vue'),
    meta: {
      isLogin: true,
      title: '个人信息'
    }
  },
  {
    path: '/businessHome',
    name: 'businessHome',
    component: () => import('../views/BusinessHome.vue'),
    meta: {
      isLogin: false,
      title: '商户首页'
    }
  },
  {
    path: '/appoint',
    name: 'appoint',
    component: () => import('../views/AppointView.vue'),
    meta: {
      isLogin: true,
      title: '预约就诊'
    }
  },
  {
    path: '/myAppoint',
    name: 'myAppoint',
    component: () => import('../views/MyAppoint.vue'),
    meta: {
      isLogin: true,
      title: '我的预约'
    }
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return {
      left: 0, top: 0
    }
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.isLogin) {
    const { token } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
    if (!token) {
      // 还需要实时验证token是否有效
      showToast('您还没有登录， 请先登录');
      return next('/login');
    }
  }
  next();
  if (to.meta.title) {
    document.title = <string>to.meta.title;
  }
})
export default router
